package com.ojoin.trade.supplyloan_core.web.messagequeue;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ojoin.trade.common.utils.CacheUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.web.domain.Dict;
import com.ojoin.trade.common.web.service.DictService;
import com.ojoin.trade.supplyloan_core.web.domain.CatchDataResultMessage;
import com.ojoin.trade.supplyloan_core.web.domain.JedisObject;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanStatTotal;
import com.ojoin.trade.supplyloan_core.web.service.TbCatchdataStrategyService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanStatTotalService;
import com.ojoin.trade.supplyloan_core.web.service.impl.CatchDataMessageServiceImpl;
import com.ojoin.trade.supplyloan_core.web.task.SLcatchDataTask;

/**
 * 
 * @author liang
 * @description 队列消息监听器
 * 
 */

@Component
public class QueueReceiverCatachListener implements MessageListener {
	@Autowired
	public CatchDataMessageServiceImpl catchDataMessageService;

	@Autowired
	public TbCatchdataStrategyService catchdataStrategyService;
	
	@Autowired
	private TbSlLoanStatTotalService statTotalService;
	
	@Autowired
	private DictService dictService;

	private static Logger log = LoggerFactory
			.getLogger(QueueReceiverCatachListener.class);

	@Override
	public void onMessage(Message message) {

		LogUtils.info(log, "comsumer recevies message");

		if (message instanceof ObjectMessage) {
			ObjectMessage om = (ObjectMessage) message;
			deal(om);
		} else if (message instanceof TextMessage) {
			LogUtils.info(log, "message instanceof TextMessage");
		}
	}

	public void deal(ObjectMessage om) {

		try {
			Object ob = om.getObject();
			if (ob instanceof CatchDataResultMessage) {
				CatchDataResultMessage ca = (CatchDataResultMessage) ob;
				catchDataMessageService.filter(ca);

				CacheUtils.remove(CacheUtils.SL_CATCHDATA_TASK, ca.getPlatformUser()
						.getId() + "");

			} else if (ob instanceof TbSlLoanStatTotal) {
				TbSlLoanStatTotal total = (TbSlLoanStatTotal) ob;
				
				statTotalService.deleteTbSlLoanTotalByPlatformUserIDAndDate(
						total.getIdOfPlatformUser(), TimeUtils.getCurDate());

				statTotalService.insert(total);

			}else if(ob instanceof JedisObject){
				JedisObject dict = (JedisObject)ob;
			    CacheUtils.put(CacheUtils.COOKIE, dict.getKey(), dict);
			} else {
				LogUtils.info(log,
						"ob instanceof CatchDataResultMessage  is false ");
			}

		} catch (JMSException e) {
			LogUtils.error(log, e);
		}

	}
}
